package org.particlethink.service.procure;

import kotlin.Pair;
import org.particlethink.dto.OrderStatusAndCount;
import org.particlethink.entry.OrderStatus;
import org.particlethink.exception.NoPermissionException;
import org.particlethink.exception.StatusException;
import org.particlethink.model.Deliver;
import org.particlethink.model.Order;
import org.particlethink.response.OrderStatusCountResponse;
import org.particlethink.service.OrderService;
import org.particlethink.utils.ListUtilsKt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class SupplierUserImpl extends CompanyUserImpl {//企业用户

    @Autowired
    private OrderService orderService;

    //发货 创建发货单计划
    //查看订单列表（状态）

    public List<Order> orderListByStatus(int supplierId, OrderStatus status, int offset, int limit) {
        return this.orderMapper.selectBySupplierIdAndStatus(supplierId, status, offset, limit);
    }


    //拒绝订单
    public void refuse(List<Integer> supplierIds, Integer orderId, String refuseReason) {
        //保存数据库
        orderService.refuse(orderId, refuseReason, order -> supplierIds.contains(order.getSupplierId()));
    }

    public OrderStatusCountResponse countOrdersByStatus(List<Integer> supplierIds, List<Integer> projectIds) {

        List<OrderStatusAndCount> orderStatusAndCounts = this.orderMapper.countByStatus(supplierIds, projectIds);
        Map<OrderStatus, Integer> orderStatusIntegerMap = ListUtilsKt.mapKV(orderStatusAndCounts, (orderStatusAndCount) -> new Pair<>(orderStatusAndCount.getStatus(), orderStatusAndCount.getCount()));

        return new OrderStatusCountResponse(
                orderStatusIntegerMap.getOrDefault(OrderStatus.Unshipped,0),
                orderStatusIntegerMap.getOrDefault(OrderStatus.InProgress,0),
                orderStatusIntegerMap.getOrDefault(OrderStatus.Done,0),
                orderStatusIntegerMap.getOrDefault(OrderStatus.Refuse,0)
        );
    }

    //完成发货
    @Transactional
    public void complete(List<Integer> supplierIds, Integer orderId) {
        Order order = this.orderMapper.selectByPrimaryKey(orderId);

        if (order == null) {
            return;
        }
        if (!order.canStop()) {
            throw new StatusException();
        }

        if (!supplierIds.contains(order.getSupplierId())) {
            throw new NoPermissionException();
        }
        List<Deliver> delivers = this.deliverMapper.selectByOrderId(orderId);
        order.setCompleted(true);
        orderService.complete(order, delivers);

    }

}
